package org.coderfun.fieldmeta.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import klg.common.dataaccess.BaseServiceImpl;
import klg.query.jpa.expr.AExpr;

import java.util.List;

import org.coderfun.fieldmeta.auth.AuthService;
import org.coderfun.fieldmeta.common.SystemCode;
import org.coderfun.fieldmeta.dao.ProjectDAO;
import org.coderfun.fieldmeta.entity.Project;
import org.coderfun.fieldmeta.entity.Project_;

@Service
public class ProjectServiceImpl  extends BaseServiceImpl<Project, Long> implements ProjectService{
	@Autowired
	ProjectDAO projectDAO;

	@Autowired
	AuthService authService;
	
	@Transactional
	@Override
	public Project save(Project entity) {
		// TODO Auto-generated method stub
		changeDefault(entity);
		return super.save(entity);
	}
	
	@Transactional
	@Override
	public Project update(Project entity) {
		// TODO Auto-generated method stub
		changeDefault(entity);
		return super.update(entity);
	}
	
	
	@Transactional
	@Override
	public void changeDefault(Project project) {
		// TODO Auto-generated method stub
		if(project.getIsDefaultCode().equals(SystemCode.YES)){
			List<Project> projects=projectDAO.findList(
					AExpr.eq(Project_.workspaceId, authService.getWorkspaceId()),
					AExpr.eq(Project_.isDefaultCode, SystemCode.YES));
			for(Project p:projects){
				p.setIsDefaultCode(SystemCode.NO);
				projectDAO.save(p);
			}
		}	
	}
}
